<template>
    <view>
        <uni-nav-bar id="nav" class="u-f-ajc" :height="modelType == 'pad'?54:44" :statusBar="true" :fixed="true">
            <view slot="left"  style="width: 50px;" @click="backAction()">
                <uni-icons type="back" size="25"></uni-icons>
            </view>
            <view class="" style="width: 100%;" :style="{lineHeight: modelType == 'pad'?'54px':'44px'}">
                <template>
                    <view class="u-f-r u-f-ac u-f-ajc" style="width: 100%;">
                        <view class="navTitle" style="font-weight: 800">{{$t('General.add.position')}}</view>
                    </view>
                </template>
            </view>
        </uni-nav-bar>
        <!-- 分享 -->
        <view v-if="type === 0">
            <view style="width: 100%; height: 100vh">
                <checkbox-group @change="radioChange">
                    <view style="font-size: 26rpx; color: #999999; padding: 20rpx">{{ group.groupName }}</view>
                    <template v-for="(item, index) in userList">
                        <label style="background-color: #FF0025;" color="#FF0025" :key="item.id" class="item" v-if="!item.isAdmin">
                            <view>{{ item.userName }}</view>
                            <view>
                                <checkbox :value="item.id" :checked="false" />
                            </view>
                        </label>
                    </template>
                </checkbox-group>
            </view>
            <view class="bottom-fixed">
                <button type="primary" class="block" @tap="onBindtapSubmit">{{$t('General.add.confirm')}}</button>
            </view>
        </view>

        <!-- 移动设备到房间 -->
        <view v-if="type == 1||type==2||type==3">
            <view style="width: 100%; height: 100vh">
                <radio-group @change="radioChange">
                    <view style="font-size: 26rpx; color: #999999; padding: 20rpx">{{ group.groupName }}</view>
                    <label color="#FF0025" class="item" v-for="(item, index) in roomList" :key="item.roomId">
                        <view>{{ item.roomName }}</view>
                        <view>
                            <radio :value="item.id" :checked="item.id === device.roomId" />
                        </view>
                    </label>
                </radio-group>
            </view>
            <view class="bottom-fixed">
				<button type="primary" class="block radius-btn" @tap="onBindtapSubmit">{{$t('General.add.confirm')}}</button>
            </view>
        </view>
    </view>
</template>

<script>
// pages/device/device/select-room/select-room.js
export default {
    data() {
        return {
            type: null,
            // 从哪一个页面跳转过来的
            device: {
                roomId: ''
            },
            roomList: [],
            roomId: '',
            userList: [],
            userId: '',
            group: {
                groupName: ''
            },
            modelType: null,
			connecttype: "", //配网类型
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
		this.connecttype = options.connecttype
		this.type = Number(options.type)
		let enData = decodeURIComponent(options.device)
		this.device = JSON.parse(enData)
		// if(this.type == 1 || this.type == 3){
		// 	let deviceList = uni.getStorageSync('deviceList');
		// 	for (let i = 0; i < deviceList.length; i++) {
		// 		const item = deviceList[i];
		// 		if (item.deviceNo === this.device.deviceNo) {
		// 			this.device.roomId = item.roomId;
		// 			break;
		// 		}
		// 	}
		// }
		this.$logs({info:'选择房间',type:this.type,device:this.device,deviceList:uni.getStorageSync('deviceList'),roomId:this.device.roomId})
		
    },
    onShow: function () {
        if (this.type === 0) {
            this.getUserListByPage();
        } else {
            // this.getRoomListByPage();
			this.getDeviceListByPage()
        }
		
    },
	onUnload() {
		uni.$emit('deviceLogout',{isBack:false})
	},
    onReady() {
        uni.getSystemInfo({
            success: (res) => {
                console.log('系统信息', res);
                this.modelType = res.deviceType;
                let navHeight = this.modelType == 'pad' ? 54 : 44
            }
        });
    },
    methods: {
        backAction() {
            console.log('点击了返回')
            if(this.type == 1) {
                uni.showModal({
                    title: this.$t('General.family.tip'),
                    content: this.$t('General.add.addTips11'),
                    success: (res) => {
                        if(res.confirm) {
                            // 点击确定
                            console.log('返回首页', res)
                            uni.switchTab({
                                url:'/jvss/pages/device/home'
                            })

                        } else if(res.cancel) {
                            // 点击取消
                        }

                    },
                    fail: () => {}
                })
            } else {
                uni.navigateBack()
            }

        },
			getDeviceListByPage(type) {
				const data = {
					userGroupId: uni.getStorageSync('currentGroupId'),
					page: 1,
					limit: 999,
					deviceNo: this.device.deviceNo
				};
				getApp().globalData.api.getDeviceListByPage(data, (result) => {
					console.log('设备最新消息===', result);
					if(result.data.length>0){
						this.device.roomId = result.data[0].roomId || ''
					}
					this.getRoomListByPage();
				})
			},
			// 查询用户组列表
			getRoomListByPage() {
				uni.showLoading({
					mask: true
				})
				const data = {
					userGroupId: uni.getStorageSync('currentGroupId'),
					//getApp().globalData.currentGroupId,
					page: 1,
					limit: 999
				};
				getApp().globalData.api.getRoomListByPage(data, (result) => {
					uni.hideLoading()
					let roomList = result.data;
					this.roomList = roomList
					if (!this.device.roomId) {
						this.device.roomId = this.roomList[0].id
						this.roomId = this.roomList[0].id
					} else {
						this.roomId = this.device.roomId
					}
					if (this.type == 1) {
						this.device.roomId = this.roomList[0].id
					}
				});
			},

			// 查询用户列表
			getUserListByPage() {
				const data = {
					userGroupId: uni.getStorageSync('currentGroupId'),
					//getApp().globalData.currentGroupId,
					page: 1,
					limit: 999
				};
				getApp().globalData.api.getUserListByPage(data, (result) => {
					console.log('查询用户列表:', result);
					let userList = result.data;
					this.userList = userList
				});
			},
			// 选择
			radioChange(ev) {
				console.log(ev);
				if (this.type === 0) {
					let userId = ev.detail.value;
					this.userId = userId
				} else {
					let roomId = ev.detail.value;
					this.roomId = roomId
				}
			},
			// 确认
			onBindtapSubmit(ev) {
				// 添加权限给成员
				if (this.type === 0) {
					const data = {
						groupId: uni.getStorageSync('currentGroupId'),
						// getApp().globalData.currentGroupId,
						deviceNo: this.device.deviceNo,
						userId: this.userId
					};
					getApp().globalData.api.addDeviceToUser(data, (result) => {
						uni.switchTab({
							url: '/jvss/pages/device/home'
						});
					});
				} // 移动设备到房间
				else if (this.type == 1 || this.type == 3) {
					uni.showLoading({
						mask: true
					});
					if (!this.roomId) {
						return uni.showToast({
							title: this.$t('General.add.addTips12'),
							icon: 'none'
						})
					}
					const data = {
						userGroupId: uni.getStorageSync('currentGroupId'),
						// getApp().globalData.currentGroupId,
						deviceNo: [this.device.deviceNo],
						roomId: this.roomId
					};
					getApp().globalData.api.moveDeviceToRoom(data, (result) => {
						console.log(result, '添加设备移动房间')
						setTimeout(() => {
							uni.hideLoading();
							// let deviceList = uni.getStorageSync('deviceList');
							// console.log(deviceList, 'deviceList')
							// for (let i = 0; i < deviceList.length; i++) {
							// 	const item = deviceList[i];
							// 	if (item.deviceNo === this.device.deviceNo) {
							// 		item.roomId = this.roomId;
							// 		break;
							// 	}
							// }
							// console.log(deviceList,'修改完重新缓存')
							// uni.setStorageSync('deviceList', deviceList);
							let bossDeviceList = uni.getStorageSync('bossDeviceList')
							let groupList = uni.getStorageSync('groupList')
							let arr
							if(result.data.code == 2000){
								for (let i = 0; i < bossDeviceList.length; i++) {
									const item = bossDeviceList[i];
									if (item.deviceNo === this.device.deviceNo) {
										item.roomId = this.roomId;
										// 根据id获取变更的房间名称
										arr = this.roomList.filter(res => res.id === item.roomId)
										item.roomName = arr[0].roomName
										break;
									}
								}
								uni.setStorageSync('bossDeviceList', bossDeviceList);
								if (this.type == 1) {
									console.log('type = 1')
									// uni.navigateTo({
									// 	url: '/jvss/pagesDevice/device/bluetooth/equipment-guide?device=' +
									// 		encodeURIComponent(JSON.stringify(this.device))+'&connecttype='+this.connecttype
									// })
									uni.reLaunch({
									    url:'/jvss/pages/device/home'
									})
								} else {
									let roomData = {
										sn: this.device.deviceNo,
										roomId: this.roomId
									}
									uni.$emit('moveRoom', roomData)
									uni.$emit('updateDevicePosition', bossDeviceList)
									uni.navigateBack(1)
								}
							}else{
								switch (this.connecttype){
									case 'qrcode':
										this.$postPointData({code:'401207', eventName:'qr_add_to_room_failed',reason:result.data.msg,error_code:result.data.code})
										break;
									case 'wifi':
										this.$postPointData({code:'401009', eventName:'wifi_add_to_room_failed',reason:result.data.msg,error_code:result.data.code})
										break;
									case 'bluetooth':
										this.$postPointData({code:'401110', eventName:'bluetooth_add_to_room_failed',reason:result.data.msg,error_code:result.data.code})
										break;
								}
							}
							console.log(this.roomList);

						}, 800)
					},false,false);
				} else if (this.type == 2) {
					this.addDevice()
				}
			},
			//蓝牙配网成功后添加上的设备添加到房间
			addDevice() {
				if (!this.roomId) {
					return uni.showToast({
						title: this.$t('General.add.addTips12'),
						icon: 'none'
					})
				}
				const data = {
					deviceNo: [this.device.deviceNo],
					roomId: this.roomId
				};
				getApp().globalData.api.addDeviceToRoom(data, (result) => {
					uni.showModal({
						title: this.$t('General.family.tip'),
						content: this.$t('General.add.addTips14'),
						showCancel: false,
						confirmText: this.$t('General.add.addTips13'),
						success: (res) => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/jvss/pages/device/home'
								});
							} else {
								uni.navigateBack({
									delta: 1
								});
							}
						}
					});
				});
			}
		}
	};
</script>
<style lang="scss">
	.item {
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		background: #ffffff;
		border-bottom: 1px solid #eeeeee;
	}

	.item:hover {
		background: #eeeeee;
	}
	::v-deep.uni-radio-input{
		background-color: #FF0025 !important;
		border-color:'#FF0025' !important;
	}
</style>
